import request from '@/util/request'

function fixCheckNum(object, key) {
  object[key] = object[key] === null ? 0 : parseInt(object[key])
}

function process(question) {
  const keyList = ['pass_num', 'fail_num', 'check_num']
  question.options = JSON.parse(question.options)
  keyList.forEach(key => fixCheckNum(question.check_status, key))
  keyList.forEach(key => fixCheckNum(question.exam_status, key))
  return question
}

export function fetchQuestions(page, query = {}) {
  return request({
    url: '/questions',
    method: 'get',
    params: {
      ...query,
      page
    }
  }).then(data => {
    data.data = data.data.map(q => process(q))
    return data
  })
}

export function createQuestion(data) {
  return request({
    url: '/questions',
    method: 'post',
    data
  })
}

export function updateQuestion(id, data) {
  return request({
    url: `/questions/${id}`,
    method: 'put',
    data
  })
}

export function removeQuestion(id) {
  return request({
    url: `/questions/${id}`,
    method: 'delete'
  })
}

export function updateGraph(id, graph) {
  const data = new FormData()
  data.append('graph', graph)
  return request({
    url: `/questions/${id}/graph`,
    method: 'post',
    data
  })
}

export function fetchNextQuestion() {
  return request({
    url: '/check/next',
    method: 'get'
  }).then(data => {
    return process(data)
  })
}

export function checkQuestion(id, status) {
  return request({
    url: `/questions/${id}/check`,
    method: 'put',
    data: {
      status
    }
  })
}

export function examQuestion(id, status) {
  return request({
    url: `/questions/${id}/exam`,
    method: 'put',
    data: {
      status
    }
  })
}
